import {LogHelper} from "../utils/logHelper";

class CreepFactory {
  public static generateCreep(room: Room, controllerLevel: number,creepsConfig:any): void {
    const controllerConfig = creepsConfig.find((config:any) => config.controllerLevel === controllerLevel);

    if (!controllerConfig) {
      return;
    }

    for (const creepConfig of controllerConfig.creeps) {
      let { role, count, body, bodyWeight,bodyEnergy } = creepConfig;
      const creeps = Object.values(Game.creeps).filter((creep) => creep.memory.role === role && creep.room.name === room.name);
      
      if (creeps.length < count) {
        const creepName = `${role}_${Game.time}`;
        const spawn = room.find(FIND_MY_SPAWNS)[0];
        if (spawn && !spawn.spawning && room.memory.spawnAllow) {
          if(!body || body.length === 0){
            body = room.calculateCreepBody(bodyWeight,bodyEnergy);
          }
          let result = spawn.spawnCreep(body, creepName, { memory: { role,bornRoom:room.name,working:false } });
          if (result === OK) {
            LogHelper.info(`房间[${room.name}] 生成新Creep 角色 ${role} 名字 ${creepName}`);
          }
          else if(result === -6){

          }
          else{
            LogHelper.warn(`房间[${room.name}] 生成新Creep失败 角色 ${role} 返回错误代码 ${result}`);
          }
          room.memory.spawnAllow = false;
        }
      }
    }
  }

  public static deleteInvalidMemory(){
    // 删除快死亡的 Creep 的 memory
    for (const name in Memory.creeps) {
      const creep = Game.creeps[name];
      if (!creep) {
        delete Memory.creeps[name];
        LogHelper.log(`房间[未知] 事件 --> 清除内存不存在的Creep 名字 ${name}`);
      } 
    }
  }
}

export { CreepFactory };